<?php
/**
 * Anniversary.php
 * 文件描述 纪念日控制器
 * Created on 2020/8/31 11:46
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\xiangji\controller;


use app\Request;
use app\xiangji\BaseController;
use app\common\helpers\Response;
use app\xiangji\services\AnniversaryService;
use think\App;
use think\exception\ValidateException;

class Anniversary extends BaseController
{
    private $anniversaryService;

    public function __construct(AnniversaryService $anniversaryService)
    {
        $this->anniversaryService = $anniversaryService;
    }

    /**
     * @todo 纪念日列表查询
     * @param Request $request
     * @return \think\response\Json
     */
    public function index(Request $request)
    {
        $result = $this->anniversaryService->search($request);
        return $this->success($result);
    }

    /**
     * @todo 纪念日详情
     * @param $id
     * @return \think\response\Json
     */
    public function show(Request $request)
    {
        $result = $this->anniversaryService->show($request);
        return $this->success($result);
    }

    public function latestAnniversaries()
    {
        $result = $this->anniversaryService->latest();
        return $this->success($result);
    }

    /**
     * @todo 添加纪念日
     * @param Request $request
     * @return \think\response\Json
     */
    public function store(Request $request)
    {
        try {
            validate(\app\common\validates\Anniversary::class)->scene('store')->check($request->post(['title', 'date', 'bg_img']));
            $result = $this->anniversaryService->store($request);
            return $this->success($result);
        }catch (ValidateException $exception){
            return $this->failed($exception->getError(), Response::HTTP_BAD_REQUEST);
        }
    }

    public function update(Request $request)
    {
        try {
            validate(\app\common\validates\Anniversary::class)->scene('update')->check($request->put(['title', 'date', 'bg_img']));
            $result = $this->anniversaryService->update($request);
            return $this->success($result);
        }catch (ValidateException $exception){
            return $this->failed($exception->getError(), Response::HTTP_BAD_REQUEST);
        }
    }

    public function del(Request $request)
    {
        $id = $request->delete('id', 0);
        $result = $this->anniversaryService->del($id);
        return $this->success($result);
    }
}
